package com.iursp.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Service;

import com.iursp.domain.model.user.CommonUser;
import com.iursp.domain.model.user.User;
import com.iursp.mapper.user.UserMapper;
import com.iursp.service.role.AuthRoleService;

@Service
public class MyUserDetailsService  implements UserDetailsService, SocialUserDetailsService{

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private AuthRoleService authRoleService;
	
	/**
	 * 
	 * <p>Title: loadUserByUsername</p>   
	 * <p>Description: 从数据库查询数据</p>   
	 * @param username
	 * @return
	 * @throws UsernameNotFoundException   
	 * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
	 */
	@Override
	@SuppressWarnings("all")
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		 String permissions = "";
		 BCryptPasswordEncoder bEncoder =new BCryptPasswordEncoder();
		 User user = userMapper.selectUserByNameOrMobile(username,username);
		 if(user != null) {
				permissions = authRoleService.selectByUserRefid(user.getRefid());
			 String password = bEncoder.encode(user.getUserPassword());
			 List<GrantedAuthority> list = AuthorityUtils.commaSeparatedStringToAuthorityList(permissions);
			 return new CommonUser(user.getRefid(),user.getUserName(),password, AuthorityUtils.commaSeparatedStringToAuthorityList(permissions));
		 }else{
	            throw new BadCredentialsException("用户名不存在！");
	        }
	}
	
	@Override
	public SocialUserDetails loadUserByUserId(String arg0) throws UsernameNotFoundException {
		// TODO Auto-generated method stub
		return null;
	}

}
